package com.danhuang.cloud.danhuanggateway.config;

import cn.hutool.json.JSONUtil;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import reactor.core.publisher.Mono;

import java.util.List;

@Configuration
public class RouteDefaultConfig {

    private final String dataId = "danghuang-routes";
    private final String group = "DEFAULT_GROUP";
    @Value("${spring.cloud.nacos.discovery.server-addr}")
    private String serverAddr;
    @Autowired
    private RouteDefinitionWriter routeDefinitionWriter;


    @Bean
    public RefreshRoutesEvent customRouteLocator(RouteLocatorBuilder builder) throws NacosException {
        ConfigService configService = NacosFactory.createConfigService(serverAddr);
        String s = configService.getConfig(dataId, group, 5000);
        List<RouteDefinition> gatewayRouteDefinitions = JSONUtil.toList(s, RouteDefinition.class);
        gatewayRouteDefinitions.forEach(e-> routeDefinitionWriter.save(Mono.just(e)).subscribe());
        return new RefreshRoutesEvent(this.routeDefinitionWriter);
    }

}
